<script setup>
import { ref, onMounted, computed, shallowRef, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useDocumentStore } from '@/stores/document';
import { useTemplateStore } from '@/stores/template';
// 导入wangEditor
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
// 导入Element Plus的消息组件
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const documentStore = useDocumentStore();
const templateStore = useTemplateStore();

// 模板ID（如果从模板创建）
const templateId = computed(() => route.query.templateId);

// 文档信息
const documentTitle = ref('');
const documentContent = ref('');

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 编辑器内容
const editorValue = ref('');

// 编辑器配置
const editorConfig = {
  placeholder: '请输入文档内容...',
  MENU_CONF: {}
};

// 模板列表
const templates = ref([]);
const selectedTemplateId = ref(null);

// 加载状态
const loading = ref({
  templates: false,
  template: false,
  creating: false
});

// 错误信息
const error = ref(null);

// 获取模板列表
const fetchTemplates = async () => {
  loading.value.templates = true;
  try {
    await templateStore.fetchTemplates(1, 20); // 修改为最大30条，符合后端限制
    templates.value = templateStore.templates;
  } catch (err) {
    console.error('Failed to fetch templates:', err);
  } finally {
    loading.value.templates = false;
  }
};

// 获取模板详情
const fetchTemplateById = async (id) => {
  if (!id) return;
  
  loading.value.template = true;
  try {
    await templateStore.fetchTemplateById(id);
    const template = templateStore.currentTemplate;
    
    if (template) {
      documentTitle.value = `基于 ${template.name} 的文档`;
      documentContent.value = template.content;
      editorValue.value = template.content; // 设置编辑器内容
    }
  } catch (err) {
    console.error(`Failed to fetch template ${id}:`, err);
  } finally {
    loading.value.template = false;
  }
};

// 选择模板
const selectTemplate = async (id) => {
  selectedTemplateId.value = id;
  await fetchTemplateById(id);
};

// 创建文档
// 创建文档
const createDocument = async () => {
  if (loading.value.creating) return;
  
  // 验证表单
  if (!documentTitle.value.trim()) {
    error.value = '请输入文档标题';
    return;
  }
  
  loading.value.creating = true;
  error.value = null;
  
  try {
    const newDocumentId = await documentStore.createDocument(
      documentTitle.value,
      editorValue.value, // 使用编辑器的内容
      selectedTemplateId.value
    );
    
    if (newDocumentId) {
      // 创建成功，跳转到编辑页面
      router.push(`/documents/${newDocumentId}`);
    } else {
      error.value = '创建文档失败';
    }
  } catch (err) {
    console.error('Failed to create document:', err);
    error.value = '创建文档失败: ' + (err.message || '未知错误');
  } finally {
    loading.value.creating = false;
  }
};

// 返回文档列表
const goBack = () => {
  router.push('/documents');
};

// 组件挂载时获取数据
onMounted(async () => {
  await fetchTemplates();
  
  // 如果URL中有模板ID，则选择该模板
  if (templateId.value) {
    selectTemplate(templateId.value);
  }
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<template>
  <div class="document-create-container">
    <div class="document-create-header">
      <h1 class="page-title">创建新文档</h1>
      <button @click="goBack" class="back-btn">
        <span class="icon">←</span> 返回
      </button>
    </div>

    <!-- 显示所选模板名称 -->
    <div v-if="selectedTemplateId" class="selected-template-info">
      <h2 class="template-info-title">使用模板：{{ templates.find(t => t.id === selectedTemplateId)?.name }}</h2>
    </div>

    <div class="document-create-form">
      <div class="form-group">
        <label for="documentTitle">文档标题</label>
        <input 
          type="text" 
          id="documentTitle" 
          v-model="documentTitle" 
          placeholder="请输入文档标题"
          required
        />
      </div>
      
      <div class="form-group">
        <label for="documentContent">文档内容</label>
        <!-- 工具栏 -->
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="editorConfig"
          mode="default"
        />
        <!-- 编辑器 -->
        <Editor
          style="height: 400px; overflow-y: hidden;"
          v-model="editorValue"
          :defaultConfig="editorConfig"
          mode="default"
          @onCreated="editorRef = $event"
        />
      </div>
      
      <div v-if="error" class="error-message">
        {{ error }}
      </div>
      
      <div class="form-actions">
        <button 
          @click="createDocument" 
          class="create-btn" 
          :disabled="loading.creating"
        >
          {{ loading.creating ? '创建中...' : '创建文档' }}
        </button>
      </div>
    </div>

    <div class="templates-section">
      <h2 class="section-title">从模板创建</h2>
      
      <div v-if="loading.templates" class="loading-placeholder">
        <p>加载模板中...</p>
      </div>
      
      <div v-else-if="templates.length === 0" class="empty-state">
        <p>暂无可用模板</p>
      </div>
      
      <div v-else class="templates-grid">
        <div 
          v-for="template in templates" 
          :key="template.id" 
          class="template-card"
          :class="{ 'selected': selectedTemplateId === template.id }"
          @click="selectTemplate(template.id)"
        >
          <div class="template-card-content">
            <h3 class="template-title">{{ template.name }}</h3>
            <p class="template-category">{{ template.category }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.document-create-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.document-create-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 1.875rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background-color: transparent;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
}

.back-btn:hover {
  background-color: #f3f4f6;
}

.document-create-form {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  margin-bottom: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  margin-bottom: 0.5rem;
}

.form-group input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.error-message {
  color: #ef4444;
  font-size: 0.875rem;
  margin-bottom: 1rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
}

.create-btn {
  padding: 0.75rem 1.5rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.create-btn:hover:not(:disabled) {
  background-color: #4338ca;
}

.create-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.templates-section {
  margin-top: 3rem;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 1.5rem;
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.5rem;
}

.template-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s, border-color 0.2s;
  cursor: pointer;
  height: 150px;
  display: flex;
  flex-direction: column;
  border: 2px solid transparent;
}

.template-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.template-card.selected {
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.template-card-content {
  padding: 1.5rem;
  flex: 1;
}

.template-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 0.5rem;
  /* 文本溢出省略 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.template-category {
  font-size: 0.875rem;
  color: #6b7280;
}

/* 加载和空状态样式 */
.loading-placeholder,
.empty-state {
  padding: 3rem 0;
  text-align: center;
  color: #6b7280;
}

.selected-template-info {
  margin: 1rem 0;
  padding: 1rem;
  background-color: #f5f7fa;
  border-radius: 8px;
  border-left: 4px solid #4a6cf7;
}

.template-info-title {
  margin: 0;
  font-size: 1.2rem;
  color: #333;
  font-weight: 500;
}
</style>